
import { _decorator, Component, Node, MeshRenderer, UIMeshRenderer, Vec3, Material } from 'cc';
import yyComponent from '../../Script/Common/yyComponent';
import { Car } from './Car';
const { ccclass, property } = _decorator;

@ccclass('ShopCar')
export class ShopCar extends yyComponent {

    protected initSub() {
        this.initCarState();
    }
    protected resetSub() {
        this.resetCarState();
    }

    public show() {
        this.node.active = true;
        this.reset();
        this.autoAddPart();
    }

    @property(Material)
    protected shopCarMat: Material = null;
    @property(Car)
    protected car: Car = null;
    protected carPartFinish: boolean = false;
    protected cacheAngle: Vec3;
    protected originalAngleY: number = 45;
    protected initCarState() {
        this.car.init();
        this.carPartFinish = false;
        this.cacheAngle = new Vec3(0, this.originalAngleY, 0);
        this.car.node.eulerAngles = this.cacheAngle;
        this.car.node.layer = this.node.layer;
        setTimeout(() => {
            let children = this.car.node.children;
            for (let i = children.length - 1; i >= 0; --i) {
                children[i].getComponent(MeshRenderer).setMaterial(this.shopCarMat, 0);
                if (!children[i].getComponent(UIMeshRenderer)) {
                    children[i].addComponent(UIMeshRenderer);
                }
                children[i].layer = this.node.layer;
            }
        }, 0);
    }
    protected resetCarState() {
        this.car.reset();
        this.carPartFinish = false;
        this.cacheAngle.y = this.originalAngleY;
        this.car.node.eulerAngles = this.cacheAngle;
    }
    protected autoAddPart() {
        let count = Math.round(this.car.getTotalPartCount() / this.car.partGroupCount);
        this.car.addPartCount(count);
        if (this.car.isPartFull()) {
            setTimeout(() => {
                if (this.car.isPartFull()) {
                    this.carPartFinish = true;
                }
            }, 1000);
        } else {
            setTimeout(() => {
                this.autoAddPart();
            }, 400);
        }
    }
    protected rotate(dt: number) {
        this.cacheAngle.y += dt * 45;
        this.car.node.eulerAngles = this.cacheAngle;
    }

    public update(dt: number) {
        // if (this.carPartFinish) {
        this.rotate(dt);
        // }
    }

}
